package com.snowflakes.gruntr;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseRelation;
import com.parse.ParseUser;

public class GruntrMain extends Activity {

	private static final int LOGIN_REQUEST = 0;

	private ListView listView;
	private static ParseQueryAdapter<ParseObject> mainAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gruntr_main);

		ImageView addF = (ImageView) findViewById(R.id.ivAddFriend);
		final ImageView fReq = (ImageView) findViewById(R.id.ivFriendRequest);
		ImageView mPost = (ImageView) findViewById(R.id.ivMakePost);

		mainAdapter = new CustomAdapter(this);

		listView = (ListView) findViewById(R.id.lvPostList);
		listView.setAdapter(mainAdapter);
		mainAdapter.loadObjects();

			ParseRelation<ParseUser> relation = ParseUser.getCurrentUser().getRelation("friends");
            relation.add(ParseUser.getCurrentUser());
            ParseUser.getCurrentUser().saveInBackground();

		Thread refreshFeed = new Thread() {
			public void run() {
				while (true) {

					try {
						sleep(30000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {

						mainAdapter.loadObjects();
					}

				}
			}// public void run()
		}; // new Thread()
		refreshFeed.start();

		// This thread is used for friend polling
		// In order to get it to run repeatedly, may need to make an infinite
		// loop
		// If a friend request is found to be pending, it will cause a button to
		// appear, allowing you to accept the friend request
		// For later implementation, this can be refined
		// For example: It can cause the notification area to show that you have
		// a friend request pending
		// Also, the ability to deny friend requests is already built in. I'll
		// actually code that in when it become relevant
		// -- Aaron
		Thread friendRequestPolling = new Thread() {
			public void run() {
				while (true) {

					try {
						sleep(4000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {

						ParseUser user = ParseUser.getCurrentUser();
						ParseQuery<ParseObject> friendQuery = ParseQuery
								.getQuery("FriendRequests");
						friendQuery.whereEqualTo("Recipient", user);
						friendQuery.whereEqualTo("Accepted", "false");

						friendQuery
								.getFirstInBackground(new GetCallback<ParseObject>() {
									public void done(ParseObject request,
											ParseException e) {
										if (request != null) {
											fReq.setImageResource(R.drawable.friendrequesttrue);
										} else {
											fReq.setImageResource(R.drawable.friendrequestfalse);
										}

									}
								});

					}

				}
			}// public void run()
		}; // new Thread()
		friendRequestPolling.start();

		Thread friendAcceptedPolling = new Thread() {
			public void run() {
				while (true) {

					try {
						sleep(4000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {

						ParseUser user = ParseUser.getCurrentUser();
						ParseQuery<ParseObject> friendQuery = ParseQuery
								.getQuery("FriendRequests");
						friendQuery.whereEqualTo("Sender", user);
						friendQuery.whereEqualTo("Accepted", "true");

						friendQuery
								.findInBackground(new FindCallback<ParseObject>() {
									public void done(
											List<ParseObject> returnedUsers,
											ParseException e) {
										for (ParseObject currentUser : returnedUsers) {
											if (currentUser != null) {
												ParseUser user = ParseUser
														.getCurrentUser();
												ParseRelation<ParseUser> relation = user
														.getRelation("friends");
												relation.add(currentUser
														.getParseUser("Recipient"));
												user.saveInBackground();
												currentUser
														.deleteInBackground();
											}

										}
									}
								});

					}

				}
			}// public void run()
		}; // new Thread()
		friendAcceptedPolling.start();

		mPost.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent i = new Intent(GruntrMain.this, MakePost.class);
				startActivity(i);
			}
		});

		addF.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent i = new Intent(GruntrMain.this, AddFriend.class);
				startActivity(i);

			}
		});

		fReq.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent i = new Intent(GruntrMain.this, FriendRequests.class);
				startActivity(i);
			}
		});

	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == LOGIN_REQUEST) {
			if (resultCode == RESULT_OK) {
				Intent i = new Intent(GruntrMain.this, GruntrMain.class);
				i.putExtra("User", ParseUser.getCurrentUser().getString("name"));
				startActivity(i);
				finish();
			} else {
				Intent i = new Intent(GruntrMain.this, Goodbye.class);
				startActivity(i);
				finish();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		} else if (id == R.id.action_logout) {
			
			ParseUser.logOut();
			//ParseUser currentUser = ParseUser.getCurrentUser();

			ParseLoginBuilder builder = new ParseLoginBuilder(GruntrMain.this);
			Intent parseLoginIntent = builder
					.setAppLogo(R.drawable.orangebanner)
					.setParseLoginEnabled(true)
					.setParseLoginButtonText("Go")
					.setParseSignupButtonText("Register")
					.setParseLoginHelpText("Forgot password?")
					.setParseLoginInvalidCredentialsToastText(
							"Your email and/or password is not correct")
					.setParseLoginEmailAsUsername(true)
					.setParseSignupSubmitButtonText("Submit registration")
					.build();
			finish();
			startActivityForResult(parseLoginIntent, 0);
		} else if (id == R.id.action_post) {
			Intent i = new Intent(GruntrMain.this, MakePost.class);
			startActivity(i);
		}
		return super.onOptionsItemSelected(item);
	}

	public void displayGruntList(View view) {
		String id = (String)view.getTag();

		Intent i = new Intent(GruntrMain.this, GruntList.class);
		Bundle idData = new Bundle();
		idData.putString("id", id);
		i.putExtras(idData);
		startActivity(i);
	}
	

	public void gruntAtIt(View view) {
		String id = (String)view.getTag();

		Intent i = new Intent(GruntrMain.this, RecordGrunt.class);
		Bundle idData = new Bundle();
		idData.putString("id", id);
		i.putExtras(idData);
		startActivity(i);

	}

}
